package com.gitee.fanx.notes.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 日志切面, 打印每次网络请求
 *
 * @author fanx
 */
@Component
public class RequestInterceptor implements HandlerInterceptor {

	private Logger log = LoggerFactory.getLogger(RequestInterceptor.class);

	@Autowired
	private ObjectMapper objectMapper;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		log.debug(">>>>>>>>>>>>>>> {} {}", request.getMethod(), request.getRequestURI());
		System.out.println(request.getParameterMap().entrySet());
		log.debug("---- RequestParams: {}", objectMapper.writeValueAsString(request.getParameterMap().entrySet()));
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		log.debug("postHandle==> ModelMap: {}", modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		log.debug("postHandle==> Exception: {}", ex);
		log.debug("<<<<<<<<<<<<<<< {} {}", request.getMethod(), request.getRequestURI());
	}

}
